//
//  TSSTSegmentedCell.m
//  SimpleComic
//
//  Created by Alexander Rauchfuss on 6/14/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "TSSTSegmentedCell.h"
#import "TSSTSegmentedControl.h"
#import "TSSTImageUtilities.h"
#import "CTGradient.h"


static CTGradient * baseButtonGradient;
static CTGradient * pressedButtonGradient;



@implementation TSSTSegmentedCell


/* Setup the gradients for all cell instances. */
+ (void)initialize
{
    baseButtonGradient = [[CTGradient gradientWithBeginningColor: [NSColor colorWithCalibratedWhite: 0.65 alpha: 1.0]
                                                     endingColor: [NSColor colorWithCalibratedWhite: 0.98 alpha: 1.0]] retain];
    pressedButtonGradient = [[CTGradient gradientWithBeginningColor: [NSColor colorWithCalibratedWhite: 0.55 alpha: 1.0]
                                                        endingColor: [NSColor colorWithCalibratedWhite: 0.88 alpha: 1.0]] retain];
}



- (void)drawSegment:(int)segment inFrame:(NSRect)frame withView:(TSSTSegmentedControl *)controlView
{
    if([controlView mouseDownSegment] == segment)
    {
        [pressedButtonGradient fillRect: frame angle: 90];
        [[NSColor colorWithCalibratedWhite: 0.2 alpha: 0.2] set];
    }
    else
    {
        [baseButtonGradient fillRect: frame angle: 270];
        [[NSColor colorWithCalibratedWhite: 1 alpha: 0.3] set];
    }
    
    /* Stroke the edge highlights of the cell */
    [NSBezierPath strokeLineFromPoint: NSMakePoint(NSMaxX(frame) - 1, NSMinY(frame))
                              toPoint: NSMakePoint(NSMaxX(frame) - 1, NSMaxY(frame))];
    [NSBezierPath strokeLineFromPoint: NSMakePoint(NSMinX(frame) + 1, NSMinY(frame))
                              toPoint: NSMakePoint(NSMinX(frame) + 1, NSMaxY(frame))];
    
    /* Stroke the segment divider */
    [[NSColor colorWithCalibratedWhite: 0 alpha: 0.7] set];
    [NSBezierPath strokeLineFromPoint: NSMakePoint( NSMinX(frame), NSMinY(frame)) 
                              toPoint: NSMakePoint( NSMinX(frame), NSMaxY(frame))];
    
    /* If the segment is selected an alternate image is grabbed. */
    NSImage * icon = nil;
    if([controlView isSelectedForSegment: segment] && [self trackingMode] != NSSegmentSwitchTrackingMomentary)
    {
        NSString * imageName = [NSString stringWithFormat: @"%@_sel", [[self imageForSegment: segment] name]];
        icon = [NSImage imageNamed: imageName];
    }
    else
    {
        icon = [self imageForSegment: segment];
    }
    
    if(icon)
    {
        NSRect imageRect = rectWithSizeCenteredInRect([icon size], frame);
        [icon setFlipped: [controlView isFlipped]];
        [icon drawInRect: imageRect fromRect: NSMakeRect( 0, 0, NSWidth(imageRect), NSHeight(imageRect)) 
               operation: NSCompositeSourceOver fraction: 1.0];
    }
}


@end

